<template>
  <div class="fill-height">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon"><DataAnalysis /></el-icon>
          环境监控详情
        </h1>
        <el-button
          type="primary"
          @click="loadData"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
      <div class="sub-header">
        <span class="executor-id">执行器ID: {{ registerKey }}</span>
        <span class="app-name">应用名称: {{ latestData.appName }}</span>
      </div>
    </div>

    <!-- 实时数据概览 -->
    <el-row :gutter="16" class="overview-cards">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-label">CPU使用率</div>
            <v-chart :option="cpuChartOption" style="height: 120px" />
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-label">系统内存使用率</div>
            <v-chart :option="memoryChartOption" style="height: 120px" />
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-label">JVM堆内存使用率</div>
            <v-chart :option="heapChartOption" style="height: 120px" />
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-label">线程数</div>
            <div class="thread-info">
              <div class="thread-count">{{ latestData.threadCount || 0 }}</div>
              <div class="thread-label">总数</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 系统和JVM信息 -->
    <el-row :gutter="16">
      <el-col :span="12">
        <el-card class="info-card" header="操作系统信息">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="系统名称">{{ latestData.osName }}</el-descriptions-item>
            <el-descriptions-item label="系统版本">{{ latestData.osVersion }}</el-descriptions-item>
            <el-descriptions-item label="架构">{{ latestData.osArch }}</el-descriptions-item>
            <el-descriptions-item label="CPU核心数">{{ latestData.cpuCores }}</el-descriptions-item>
            <el-descriptions-item label="系统负载">{{ latestData.systemLoadAverage }}</el-descriptions-item>
            <el-descriptions-item label="运行时间">{{ formatUptime(latestData.uptimeSeconds) }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="info-card" header="JVM信息">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="JVM版本">{{ latestData.jvmVersion }}</el-descriptions-item>
            <el-descriptions-item label="JVM厂商">{{ latestData.jvmVendor }}</el-descriptions-item>
            <el-descriptions-item label="JVM启动时间">{{ formatDateTime(latestData.jvmStartTime) }}</el-descriptions-item>
            <el-descriptions-item label="JVM运行时间">{{ formatUptime(latestData.jvmUptime) }}</el-descriptions-item>
            <el-descriptions-item label="总线程数">{{ latestData.threadCount }}</el-descriptions-item>
            <el-descriptions-item label="守护线程数">{{ latestData.daemonThreadCount }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <!-- 历史数据图表 -->
    <el-card class="chart-card" header="历史趋势">
      <div class="history-controls">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
        />
        <el-button type="primary" @click="loadHistoryData">查询历史</el-button>
      </div>
      <v-chart :option="historyChartOption" style="height: 400px" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { DataAnalysis, Refresh } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, GaugeChart } from 'echarts/charts'
import { GridComponent, TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { environmentMonitorApi } from '@/services/api'
import type { EnvironmentMonitorVO, EnvironmentMonitorHistoryQueryDTO, ApiResult } from '@/types/job'

// 注册 ECharts 组件
use([CanvasRenderer, LineChart, GaugeChart, GridComponent, TitleComponent, TooltipComponent, LegendComponent])

const route = useRoute()
const registerKey = route.params.registerKey as string

// 响应式数据
const loading = ref(false)
const latestData = ref<Partial<EnvironmentMonitorVO>>({})
const historyData = ref<EnvironmentMonitorVO[]>([])
const timeRange = ref<[Date, Date]>([new Date(new Date().getTime() - 3600 * 1000), new Date()])

// 创建仪表盘图表配置的函数
const createGaugeOption = (name: string, value: number, color: any) => {
  return {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 4,
        itemStyle: {
          color: color
        },
        progress: {
          show: true,
          width: 18
        },
        axisLine: {
          lineStyle: {
            width: 18
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        pointer: {
          show: false
        },
        title: {
          show: false
        },
        detail: {
          valueAnimation: true,
          fontSize: 20,
          offsetCenter: [0, '-10%']
        },
        data: [
          {
            value: value,
            name: name
          }
        ]
      }
    ]
  }
}

const cpuChartOption = computed(() => createGaugeOption('CPU', latestData.value.cpuUsagePercent || 0, '#5470c6'))
const memoryChartOption = computed(() => createGaugeOption('内存', latestData.value.systemMemoryUsagePercent || 0, '#91cc75'))
const heapChartOption = computed(() => createGaugeOption('堆内存', latestData.value.heapMemoryUsagePercent || 0, '#fac858'))

const historyChartOption = computed(() => {
  const times = historyData.value.map(d => new Date(d.monitorTime).toLocaleTimeString())
  const cpuUsages = historyData.value.map(d => d.cpuUsagePercent)
  const memUsages = historyData.value.map(d => d.systemMemoryUsagePercent)
  const heapUsages = historyData.value.map(d => d.heapMemoryUsagePercent)

  return {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['CPU使用率', '系统内存使用率', 'JVM堆内存使用率']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: times
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} %'
      }
    },
    series: [
      {
        name: 'CPU使用率',
        type: 'line',
        data: cpuUsages,
        smooth: true,
        itemStyle: { color: '#5470c6' }
      },
      {
        name: '系统内存使用率',
        type: 'line',
        data: memUsages,
        smooth: true,
        itemStyle: { color: '#91cc75' }
      },
      {
        name: 'JVM堆内存使用率',
        type: 'line',
        data: heapUsages,
        smooth: true,
        itemStyle: { color: '#fac858' }
      }
    ]
  }
})

// 格式化运行时间
const formatUptime = (seconds?: number) => {
  if (seconds === undefined) return '-'
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (days > 0) return `${days}天${hours}小时`
  if (hours > 0) return `${hours}小时${minutes}分钟`
  return `${minutes}分钟`
}

// 格式化日期时间
const formatDateTime = (timestamp?: number) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString()
}

// 加载最新数据
const loadLatestData = async () => {
  loading.value = true
  try {
    const response: ApiResult<EnvironmentMonitorVO> = await environmentMonitorApi.queryLatestEnvironmentMonitorByRegisterKey(registerKey)
    if (response.success) {
      latestData.value = response.data
    } else {
      ElMessage.error('加载最新数据失败: ' + response.message)
    }
  } catch (error) {
    console.error('加载最新数据出错:', error)
    ElMessage.error('加载最新数据出错')
  } finally {
    loading.value = false
  }
}

// 加载历史数据
const loadHistoryData = async () => {
  loading.value = true
  try {
    const params: EnvironmentMonitorHistoryQueryDTO = {
      registerKey: registerKey,
      startTime: formatDateTimeForAPI(timeRange.value[0]),
      endTime: formatDateTimeForAPI(timeRange.value[1]),
      limit: 500
    }
    const response: ApiResult<EnvironmentMonitorVO[]> = await environmentMonitorApi.queryEnvironmentMonitorHistory(params)
    if (response.success) {
      historyData.value = response.data.sort((a,b) => new Date(a.monitorTime).getTime() - new Date(b.monitorTime).getTime());
    } else {
      ElMessage.error('加载历史数据失败: ' + response.message)
    }
  } catch (error) {
    console.error('加载历史数据出错:', error)
    ElMessage.error('加载历史数据出错')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间为API格式 (yyyy-MM-dd HH:mm:ss)
const formatDateTimeForAPI = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 加载所有数据
const loadData = () => {
  loadLatestData()
  loadHistoryData()
}

// 页面加载时执行
onMounted(() => {
  loadData()
})
</script>

<style scoped>
/* 页面布局 */
.fill-height {
  min-height: 100vh;
  padding: 20px;
  background: #f5f7fa;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.title-icon {
  margin-right: 12px;
  font-size: 28px;
  color: #f59e0b;
}

.sub-header {
  color: #64748b;
  font-size: 14px;
}
.executor-id {
  margin-right: 20px;
}

/* 概览卡片 */
.overview-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: #ffffff;
  border: 2px solid #e2e8f0;
  border-radius: 0;
  padding: 20px;
  text-align: center;
}

.stat-content {
  width: 100%;
}

.stat-label {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
}

.thread-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 120px;
}

.thread-count {
  font-size: 40px;
  font-weight: bold;
  color: #3b82f6;
}

.thread-label {
  color: #64748b;
}

/* 信息卡片 */
.info-card {
  margin-bottom: 20px;
  border: 2px solid #e2e8f0;
  border-radius: 0;
}

/* 图表卡片 */
.chart-card {
  border: 2px solid #e2e8f0;
  border-radius: 0;
}

.history-controls {
  margin-bottom: 16px;
  display: flex;
  gap: 16px;
}

/* 按钮样式 */
.el-button {
  border-radius: 0;
  font-weight: 600;
  border: 2px solid;
}
</style>
